export const usePlugin = (map: any, AMap: any) => {
  const options = {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0,
    convert: true,
    showButton: true,
    buttonPosition: 'RB',
    buttonOffset: new AMap.Pixel(10, 20),
    zoomToAccuracy: true,
  }

  const addGeolocation = () => {
    return new Promise<
      { longitude: number; latitude: number; positionName: string } | undefined
    >((resolve, reject) => {
      // 添加获取当前位置经纬度的插件
      AMap.plugin(['AMap.Geolocation'], () => {
        const geolocation = new AMap.Geolocation(options)

        // 地图定位到当前位置
        map.addControl(geolocation)

        // 获取当前位置经纬度
        geolocation.getCurrentPosition(
          (status: string, result: Record<any, any>) => {
            if (status !== 'complete') return reject({ msg: result.message })
            // 获取当前城市信息
            geolocation.getCityInfo(async (status: string, resultCity: any) => {
              if (status !== 'complete') return reject({ msg: result.message })
              // 获取当前位置
              const location = await addGeocoder(resultCity.city, [
                result.position.KL,
                result.position.kT,
              ])

              resolve({
                longitude: result.position.KL,
                latitude: result.position.kT,
                positionName: location.address,
              })
            })

            map.setCenter(result.position)
          },
        )
      })
    })
  }

  // 添加逆地址编码插件，用来获取当前位置信息
  const addGeocoder = (city: string, pos: [number, number]) => {
    return new Promise<{ address: string }>((resolve, reject) => {
      AMap.plugin(['AMap.Geocoder'], () => {
        const geocoder = new AMap.Geocoder({
          radius: 1000,
          city: city,
          extensions: 'all',
        })
        // 获取位置信息
        geocoder.getAddress(
          new AMap.LngLat(pos[0], pos[1]),
          (status: string, result: any) => {
            if (status !== 'complete') return reject({ msg: '获取位置失败' })
            resolve({ address: result.regeocode.formattedAddress })
          },
        )
      })
    })
  }

  return { addGeolocation }
}
